package com.asia5b.a5mall.middleware.utils;

import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.Typeface;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.IntRange;

import com.asia5b.a5bmall.resource.ResString;
import com.asia5b.a5mall.middleware.R;

import java.math.RoundingMode;
import java.text.DecimalFormat;

import static timber.log.Timber.d;

/**
 */

public class StringUtils {

    private static DecimalFormat twolastDF = new DecimalFormat("#0.00");
    private static DecimalFormat onelastDF = new DecimalFormat("#0.0");
    private static DecimalFormat IntlastDF = new DecimalFormat("#0");

    /**
     * 文本设置超链接
     *
     * @param context
     * @param content
     * @param linkText
     * @param localColor
     * @param textView
     */
    public static void setLinkText(String content, String linkText, TextView textView, int localColor,View.OnClickListener listener) {
        SpannableString termsofuseSpannableString = StringUtils.getSpannableString(content, linkText, localColor
                , v -> {
                    listener.onClick(v);
                });
        textView.setText(termsofuseSpannableString);
        textView.setMovementMethod(LinkMovementMethod.getInstance());
    }


    public static SpannableString getSpannableString(String text, String localText, int localColor, View.OnClickListener listener) {
        try {
            if (!TextUtils.isEmpty(text) && !TextUtils.isEmpty(localText)) {
                SpannableString spanableInfo = new SpannableString(text);
                LocalClickable localClickable = new LocalClickable(listener, localColor);
                int start = text.indexOf(localText);
                int end = start + localText.length();
                spanableInfo.setSpan(localClickable, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                spanableInfo.setSpan(new StyleSpan(Typeface.BOLD), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                return spanableInfo;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new SpannableString("");
    }

    public static SpannableStringBuilder setTextColor(String Texts, String kw, int color) {
        Texts = Texts + " ";
        if (TextUtils.isEmpty(kw) || !Texts.contains(kw)) {
            return new SpannableStringBuilder(Texts);
        }

        SpannableStringBuilder builder = new SpannableStringBuilder(Texts);

        String[] str = Texts.split(kw);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < str.length; i++) {
            if (i == 0) {
                sb.append(str[i]);
            } else {
                sb.append(kw);
                sb.append(str[i]);
            }
            str[i] = sb.length() + "," + (sb.length() + kw.length());
        }
        for (int i = 0; i < str.length - 1; i++) {
            ForegroundColorSpan redSpan = new ForegroundColorSpan(color);
            builder.setSpan(redSpan, Integer.parseInt(str[i].split(",")[0]), Integer.parseInt(str[i].split(",")[1]), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return builder;
    }



    public static String twolastDF(double d) {
//        twolastDF.setRoundingMode(RoundingMode.DOWN);//不要四舍五入
        twolastDF.setRoundingMode(RoundingMode.HALF_UP);//要四舍五入
        return twolastDF.format(d);
    }

    public static double twolastDouble(double d) {
//        twolastDF.setRoundingMode(RoundingMode.DOWN);//不要四舍五入
        twolastDF.setRoundingMode(RoundingMode.HALF_UP);//要四舍五入
        return Double.parseDouble(twolastDF.format(d));
    }

    public static String onelastDF(double d) {
//        twolastDF.setRoundingMode(RoundingMode.DOWN);//不要四舍五入
        onelastDF.setRoundingMode(RoundingMode.HALF_UP);//要四舍五入
        return onelastDF.format(d);
    }

    public static double onelastDouble(double d) {
//        twolastDF.setRoundingMode(RoundingMode.DOWN);//不要四舍五入
        onelastDF.setRoundingMode(RoundingMode.HALF_UP);//要四舍五入
        return Double.parseDouble(onelastDF.format(d));
    }

    public static int Intlast(double d) {
//        onelastDF.setRoundingMode(RoundingMode.HALF_UP);//要四舍五入
        return Integer.parseInt(IntlastDF.format(d));
    }

    public static void onClickCopy(Context context, String url) {
        ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        // 将文本内容放到系统剪贴板里。
        cm.setText(url);
        Toast.makeText(context, ResString.get(R.string.复制成功), Toast.LENGTH_LONG).show();
    }

    public static String formatNum2(double dIn) {
        if (dIn == 0) {
            return "0";
        }
        return formatNum(dIn + "", 2);
    }

    public static String formatNum2(float fIn) {
        if (fIn == 0) {
            return "0";
        }
        return formatNum(fIn + "", 2);
    }

    public static String formatNum2(String strIn) {
        return formatNum(strIn, 2);
    }

    /**
     * 千位分隔符,并且小数点后保留2位
     *
     * @param strIn 传入值
     * @param num   保留多少位
     * @return String
     */
    public static String formatNum(String strIn, @IntRange(from = 1, to = 3) int num) {
        if (TextUtils.isEmpty(strIn)) {
            return "";
        }
        String strOut;
        try {
            Double n = Double.valueOf(strIn);
            DecimalFormat df;
            if (num == 1) {
                df = new DecimalFormat("#,##0.0");
            } else if (num == 2) {
                df = new DecimalFormat("#,##0.00");
            } else {
                df = new DecimalFormat("#,##0.000");
            }
            strOut = df.format(n);
            if (strOut.indexOf(".") > 0) {
                //正则表达
//                strOut = strOut.replaceAll("0+?$", "");//去掉后面无用的零
//                strOut = strOut.replaceAll("[.]$", "");//如小数点后面全是零则去掉小数点
            }
        } catch (Exception e) {
            e.printStackTrace();
            return strIn;
        }
        return strOut;
    }


    /***
     * 获取url 指定name的value;
     * @param url
     * @param name
     * @return
     */
    public static String getValueByName(String url, String name) {
        String result = "";
        int index = url.indexOf("?");
        String temp = url.substring(index + 1);
        String[] keyValue = temp.split("&");
        for (String str : keyValue) {
            if (str.contains(name)) {
                result = str.replace(name + "=", "");
                break;
            }
        }
        return result;
    }

    // (a-b)/a的百分比
    public static int percent(String a, String b) {
        int percent = 1;
        if (TextUtils.isEmpty(a) || TextUtils.isEmpty(b)) {
            return percent;
        }
        d("--->>>>>>>>---percent:" + String.format("a:%s,b:%s", a, b));
        try {
            float aFloat = parseFloat(a);
            float bFloat = parseFloat(b);
            float cFloat = (aFloat - bFloat) / aFloat;
            twolastDF.setRoundingMode(RoundingMode.HALF_UP);
            float dFloat = Float.parseFloat(twolastDF.format(cFloat));
            percent = (int) (dFloat * 100);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return percent;
    }

    public static double parseDouble(String strIn) {
        double l = 0.0;
        d("--->>>>>>>>---parseDouble.strIn:" + strIn);
        if (TextUtils.isEmpty(strIn)) {
            return l;
        }
        try {
            l = Double.parseDouble(strIn);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return l;
    }

    public static float parseFloat(String strIn) {
        float l = 0;
        d("--->>>>>>>>---parseFloat.strIn:" + strIn);
        if (TextUtils.isEmpty(strIn)) {
            return l;
        }
        try {
            l = Float.parseFloat(strIn);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return l;
    }

    public static int parseInteger(String strIn) {
        int l = 0;
        d("--->>>>>>>>---parseInteger.strIn:" + strIn);
        if (TextUtils.isEmpty(strIn)) {
            return l;
        }
        try {
            l = Integer.parseInt(strIn);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return l;
    }

    public static long parseLong(String strIn) {
        long l = 0;
        d("--->>>>>>>>---parseInteger.strIn:" + strIn);
        if (TextUtils.isEmpty(strIn)) {
            return l;
        }
        try {
            l = Long.parseLong(strIn);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return l;
    }
}
